const { resolveInclude } = require('ejs');
const mongodb = require('mongodb');
let mongoCt = mongodb.MongoClient;
let ObjectId = mongodb.ObjectId;

let sql = 'womai';

// 开库
let open = ({ dbName = sql, collectionName = '', url = 'mongodb://127.0.0.1:27017' }) => new Promise((resolve, reject) => {
  // 检测集合名是否存在，不存在抛出错误
  mongoCt.connect(url, { useUnifiedTopology: true }, (err, client) => {
    if (err) {
      reject({ err })
    } else {
      let db = client.db(dbName)
      let collection = db.collection(collectionName)
      resolve({ collection, client, ObjectId })
    }
  })
})

// 列表
let findList = ({ dbName = sql, collectionName, _limit, _page, _sort, _q }) => {
  let rule = _q ? { $or: [ { classify: eval('/' + _q + '/') },] } : {}
  return new Promise((resolve, reject) => {
    // 开库
    open({ dbName, collectionName }).then(
      ({ collection, client }) => {
        // 查询
        collection.find(rule, { skip: _page * _limit, limit: _limit - 0, sort: { [_sort]: 1 } }).toArray((err, result) => {
          if (!err && result.length > 0) {
            // 查询成功
            resolve({ err: 0, data: result })
          } else {
            resolve({ err: 1, msg: '查无数据' })
          }
          client.close()
        })
      }).catch(
        (err) => {
          reject({ err: 1, msg: '库连接失败', data: err })
        })
  })
}

// 详情
let findDetail = ({ collectionName, dbName = sql, _id = "", _q="" }) => {
  return new Promise((resolve, reject) => {
    // 开库
   
    open({ dbName, collectionName }).then(({ collection, client }) => {
      // 开库成功，查询数据
      if ( _q.length > 0||_id.length===24) {
        // 判断_id格式 
        let rule = _q ? { username: _q } : { _id: ObjectId(_id) }
        collection.find(rule, { projection: { _id: 0 } }).toArray((err, result) => {
          if (!err && result.length > 0) {
            resolve({ err: 0, msg: '成功', data: result[0] })
          } else {
            resolve({ err: 1, msg: '查无数据' })
          }
          client.close();
        })
      } else {
        // _id格式错误
        resolve({ err: 1, msg: '_id有误，且为必传参数' })
        client.close();
      }
    }).catch(({ err }) => {
      // 开库失败
      reject({ err: 1, msg: '库连接失败', data: err })
    })
  })
}

exports.open = open
exports.findList = findList
exports.findDetail = findDetail